import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_sound/public/flutter_sound_player.dart';
import 'package:flutter_svg/svg.dart';
import 'package:interview/components/app/app_ripple_button.dart';
import 'package:interview/config/app.enum.dart';
import 'package:interview/pages/record/database_helper.dart';
import 'package:interview/theme/app_colors.dart';
import 'package:interview/utils/format.dart';
import 'package:interview/utils/logger.dart';
import 'package:flutter_slidable/flutter_slidable.dart';

class RecordList extends StatefulWidget {
  final AppColors theme;
  final void Function(String) addRecordingToList;
  final GlobalKey<AnimatedListState> listKey;
  final List<Map<String, dynamic>> recordings;
  final bool isPlaying;
  final Duration currentPosition;
  final Duration totalDuration;
  final FlutterSoundPlayer audioPlayer;
  final void Function(Duration value) updateCurrentPosition;
  final void Function(Duration value) updateTotalDuration;
  final void Function(String path) togglePlayPause;

  const RecordList({
    super.key,
    required this.addRecordingToList,
    required this.listKey,
    required this.recordings,
    required this.theme, 
    required this.isPlaying, 
    required this.currentPosition, 
    required this.totalDuration, 
    required this.audioPlayer,
    required this.updateCurrentPosition, 
    required this.updateTotalDuration, 
    required this.togglePlayPause
  });

  @override
  State<RecordList> createState() => _RecordListState();
}

class _RecordListState extends State<RecordList> {


  @override
  void initState() {
    super.initState();
    _initPlayer();
    _loadRecordingsFromDatabase(); // 加载数据库录音
  }

  @override
  void dispose() {
    widget.audioPlayer.closePlayer(); // 关闭播放器
    super.dispose();
  }



  /// 初始化播放器
  Future<void> _initPlayer() async {
    await widget.audioPlayer.openPlayer();
    widget.audioPlayer.setSubscriptionDuration(const Duration(milliseconds: 60));
  }

  /// 从数据库加载录音（支持分页）
  Future<void> _loadRecordingsFromDatabase() async {
    try {
      // 从数据库查询录音数据
      List<Map<String, dynamic>> recordings = await DatabaseHelper.instance.fetchRecordings(
        orderBy: 'create_time DESC',
        // limit: 4,
        // offset:0
      );
      // 动态插入新数据
      for (int i = 0; i < recordings.length; i++) {
        widget.recordings.add(recordings[i]);
        widget.listKey.currentState?.insertItem(i);
      }
      Logger.info("加载录音成功，数量: ${widget.recordings.length}");
    } catch (e) {
      Logger.error("加载录音失败: $e");
    }
  }



  /// 调整播放速度
  // Future<void> _changePlaybackSpeed(double speed) async {
  //   if (widget.isPlaying) {
  //     await widget.audioPlayer.setSpeed(speed);
  //   }
  //   setState(() {
  //     _playbackSpeed = speed;
  //   });
  // }


  /// 删除录音
  void deleteRecording(int index) async {
    Map<String, dynamic> removedItem = widget.recordings.removeAt(index);
    widget.listKey.currentState?.removeItem(
      index,
      (context, animation) => _buildRecordingItem(widget.theme, removedItem, animation , widget.isPlaying),
    );
    // 删除数据库记录和本地文件
    await DatabaseHelper.instance.deleteRecording(removedItem['id']);
    File(removedItem['path']).deleteSync();
  }

  

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Expanded(
          child: Container(
            width: double.infinity,
            padding: const EdgeInsets.symmetric(horizontal: 12 , vertical: 16),
            child: AnimatedList(
              key: widget.listKey,
              initialItemCount: widget.recordings.length,
              itemBuilder: (context, index, animation) {
                return _buildRecordingItem( widget.theme, widget.recordings[index], animation , widget.isPlaying);
              },
            ),
          ),
        ),
      ],
    );
  }

  /// 构建录音列表项
  Widget _buildRecordingItem(
    AppColors theme,
    Map<String, dynamic> recording, 
    Animation<double> animation,
    bool isPlaying
    ) {
    return SizeTransition(
      sizeFactor: animation,
      child: Slidable(
        key: ValueKey(recording['id']), // 每个项目的唯一标识符
        endActionPane: ActionPane(
          motion: const ScrollMotion(),
          children: [
            CustomSlidableAction(
              onPressed: (context) {
                // editRecording(recording);
              },
              backgroundColor: Colors.blue,
              foregroundColor: Colors.white,

              child: Text("编辑", style: TextStyle(fontSize: 12 , fontWeight: FontWeight.bold ))
              
            ),
            CustomSlidableAction(
              onPressed: (context) {
                int index = widget.recordings.indexOf(recording);
                deleteRecording(index);
              },
              backgroundColor: Colors.red,
              foregroundColor: Colors.white,
              child: Text("删除", style: TextStyle(fontSize: 12 , fontWeight: FontWeight.bold ))
            ),
          ],
        ),
        child: AppRippleButton(
          padding: const EdgeInsets.symmetric(vertical: 6 ,horizontal: 4),
          borderRadius: BorderRadius.circular(12),
          onTap: () {
            widget.togglePlayPause(recording['path']);
          },
          child: Row(
           mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '${DateTime.fromMillisecondsSinceEpoch(recording['create_time']).toLocal()}',
                    style: TextStyle(
                      fontSize: 13,
                      fontWeight: FontWeight.bold,
                      color: widget.theme.contrastPure,
                    ),
                  ),
                  Text(
                    Format.formatDuration(recording["duration"]),
                    style: TextStyle(
                      fontSize: 12,
                      fontWeight: FontWeight.w500,
                      color: widget.theme.contrastMix3,
                    ),
                  ),
                ],
              ),
              SvgPicture.asset("${AppEnumAssets.basePath}record.svg" , width: 28 ,height: 32,),
            ]
          )
        ),
      ),
    );
  }
}